import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Player {

	protected ArrayList<Tile> rack;
	protected String name;
	protected int score;
	protected Setup setup;
	protected int numOfTiles;
	//protected Display ownDisplay;

	public Player(int no) {
		//ownDisplay = new Display();
		name = "";
		score = 0;
		name = Display.io("Player" + no + " name:");
		rack = new ArrayList<Tile>();
		numOfTiles = 7;

	}

	protected void getTiles() {
		for (int i = rack.size() - numOfTiles; i < 0; i++) {
			Tile t = Bag.getTile();
			if (t.getLetter() != '\t') rack.add(t);
			else numOfTiles--;
		}
	}

	public boolean takeTurn() {
		
		getTiles();
		System.out.println(rack);
		String cmdLine = Display.io(name + " -> ");
		switch (parse(cmdLine)) {
		case SETUP:
			setup = new Setup(cmdLine, rack);
			Board.putSetup(setup);
			score += setup.score;
			break;
		case EXCHANGE:
			exchangeTiles(cmdLine);
			Display.displayNotification(name + " exchanging tiles");
			break;
		case CHELLANGE:
			// do chellange
			String wordToChellange = cmdLine.substring(3).replace(" ", "");
			Game.challengeLast(wordToChellange);
			break;
		case QUIT:
			Game.running = false;
			break;
		case SCOREBOARD:
			// do scoreboard
			break;
		case HELP:
			// do help
			break;
		case INVALID:
			// do help
			break;
		case PASS:
			return false;
			
		}

		return true;

	}

	
	public void exchangeTiles(String s) {
		String tiles = s.substring(s.indexOf(" ")+1);
		for (int i= 0; i < tiles.length(); i++) {
			char c = tiles.charAt(i);
			for (Tile e : rack) {
				if (e.getLetter() == c) {
					Tile tmp = Bag.exhange(e);
					rack.remove(e);
					rack.add(tmp);
					break;
				}
			}
		}
	}

	public CommandTypes parse(String s) {
		StringBuffer b;
		CommandTypes cmd;
		String command = "";
		cmd = CommandTypes.SETUP;
		b = new StringBuffer(s.toUpperCase());
		int cmdlen = s.length() > 1 ? 2 : 1;
		if (!s.isEmpty())
		command = b.substring(0, cmdlen);
		if (command.equals("EX"))
			cmd = CommandTypes.EXCHANGE;
		else if (command.equals("CH"))
			cmd = CommandTypes.CHELLANGE;
		else if (command.equals("Q"))
			cmd = CommandTypes.QUIT;
		else if (command.equals("SB"))
			cmd = CommandTypes.SCOREBOARD;
		else if (command.equals("?"))
			cmd = CommandTypes.HELP;
		else if (command.equals("P"))
			cmd = CommandTypes.PASS;
		switch (cmd) {
		case SETUP:

			Pattern p = Pattern.compile("^[a-o][1-9][0-5]?\\s[dr]\\s.*",
					Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
			Matcher m = p.matcher(s);

			if (!m.matches()) {
				cmd = CommandTypes.INVALID;

			}

			break;
		}
		return cmd;

	}
	public void updateScore(int s){
		score += s;
	}
	public int getScore(){
		return score;
	}
	/**
	 * @return the numOfTiles
	 */
	public int getNumOfTiles() {
		return numOfTiles;
	}

}
